import * as api from "@/api/api.js";
import * as config from "@/api/config.js";
import * as ChsApi from '@/api/hospital/chs.js';
import {
	WX_AUTH,
	STATE_KEY,
	BACK_URL
} from '@/config/cache';
import {
	parseQuery
} from '@/utils';
import store from '@/store';
import Cache from '@/utils/cache';

class AuthChs {

	constructor() {
		this.status = false; // 是否实例化
		this.initConfig = {};
	}
	
	/**
	 * 初始化
	 */
	Chs() {
		return new Promise((resolve, reject) => {
			ChsApi.getChsCfg().then(res => {
				console.table(res);
				this.initConfig = res.data;
				this.status = true;
				resolve(res.data);
			}).catch(err => {
				this.status = false;
				console.log('初始化失败 ', err);
				reject(err);
			});
		});
	}
	
	
	/**
	 * 用户授权
	 */
	toOauth(backUrl) {
		let that = this;
		this.Chs().then(cfg => {
			let linkUrl = cfg.channelOauthUrl;
			location.href = that.getAuthUrl(that.initConfig.appId,'04107',linkUrl,backUrl);
			// that.getAuthUrl(that.initConfig.appId,'04107',linkUrl,backUrl);
		})
	}
	
	/**
	 * 
	 * 获取跳转授权后的地址
	 */
	getAuthUrl(appId,bizType,linkUrl,backUrl) {
		console.info("appId:"+appId);
		console.info("linkUrl:"+linkUrl);
		console.info("backUrl:"+backUrl);
		let url = `${location.origin}${backUrl}`
		console.info("url:"+url);
		// if (url.indexOf('?') === -1) {
		// 	url = url + '?'
		// } else {
		// 	url = url + '&'
		// }
		console.info("url:"+url);
		const redirect_uri = encodeURIComponent(`${url}`);
		uni.removeStorageSync(BACK_URL);
		// https://card.wecity.qq.com/oauth/code?authType=2&isDepart=2&appid=%s&cityCode=%s&channel=%s&orgChnlCrtfCodg=%s&orgCodg=%s&bizType=%s&orgAppId=%s&redirectUrl=%s"
		
		const state = encodeURIComponent(
			("" + Math.random()).split(".")[1] + "authorizestate"
		);
		let authUrl = `${linkUrl}?authType=2&isDepart=2&appid=${appId}&cityCode=${this.initConfig.cityCode}&channel=${this.initConfig.channel}&orgChnlCrtfCodg=${this.initConfig.orgChnlCrtfCodg}&orgCodg=${this.initConfig.orgCodg}&bizType=${bizType}&orgAppId=${this.initConfig.orgAppId}&redirectUrl=${redirect_uri}&state=${state}`;
		console.info("authUrl:"+authUrl);
		return authUrl;
	}
	

	

}

export default new AuthChs();